package example;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

public class IncomeTaxCalculatorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws  IOException {
        // 从表单获取输入的年收入
        BigDecimal income = new BigDecimal(request.getParameter("income"));

        // 调用计算税率的方法
        BigDecimal tax = calculateTax(income);

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<h2>个人所得税：</h2>");
        response.getWriter().println("<p>年收入：" + income + " 元</p>");
        response.getWriter().println("<p>个人所得税：" + tax + " 元</p>");
    }

    private BigDecimal calculateTax(BigDecimal income) {
        // 在这里编写计算个人所得税的逻辑
        // 省略具体实现，根据国家的税法规定进行计算
        BigDecimal tax;
        if (income.compareTo(new BigDecimal("0")) <= 0) {
            tax = new BigDecimal("0");
        } else if (income.compareTo(new BigDecimal("36000")) <= 0) {
            tax = income.multiply(new BigDecimal("0.03"));
        } else if (income.compareTo(new BigDecimal("144000")) <= 0) {
            tax = income.multiply(new BigDecimal("0.1")).subtract(new BigDecimal("2520"));
        } else if (income.compareTo(new BigDecimal("300000")) <= 0) {
            tax = income.multiply(new BigDecimal("0.2")).subtract(new BigDecimal("16920"));
        } else if (income.compareTo(new BigDecimal("420000")) <= 0) {
            tax = income.multiply(new BigDecimal("0.25")).subtract(new BigDecimal("31920"));
        } else if (income.compareTo(new BigDecimal("660000")) <= 0) {
            tax = income.multiply(new BigDecimal("0.3")).subtract(new BigDecimal("52920"));
        } else if (income.compareTo(new BigDecimal("960000")) <= 0) {
            tax = income.multiply(new BigDecimal("0.35")).subtract(new BigDecimal("85920"));
        } else {
            tax = income.multiply(new BigDecimal("0.45")).subtract(new BigDecimal("181920"));
        }
        return tax.setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}
